﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Web.Services;
using System.Collections;

public partial class SurveyWeb : System.Web.UI.Page
{
    public string path;
    public string SURVEY_ID;
    public string SIP_NO;
    public string SIP_NAME;
    public DateTime END_TIME;


    protected void Page_Load(object sender, EventArgs e)
    {

        try
        {
          //正欣加的
          UserAuthorization();

          if (Request.QueryString[CF.QS_survey_id] != null)
            SURVEY_ID = CF.DecodeString(Request.QueryString[CF.QS_survey_id].ToString());

          if (Request.QueryString[CF.QS_sip_number] != null)
            SIP_NO = CF.DecodeString(Request.QueryString[CF.QS_sip_number].ToString());
          //////////

          
            lit_Result.Text = "";
            SIP_NAME = Tool_kitcs.GetUserInfo(SIP_NO, "");


            //【01】取得問卷基本資料 
            if (SURVEY_ID != "" && SIP_NAME != "")
            {
                bool[] Result = GetSurvey(SURVEY_ID);
                lbl_SIP_NAME.Text = SIP_NAME;
                if (Result[0])
                {
                    //【02-01】取得題目
                    this.PlaceHolder1.Controls.Clear();
                    GetQuestion(SURVEY_ID);
                    DisEditControls();
                    if (Result[1] == false) DisAllControls();
                }
                else
                {
                    Submit.Visible = false;
                    Reset.Visible = false;
                }
            }
            else
            {
                Submit.Visible = false;
                Reset.Visible = false;
            }

        }
        catch (Exception exception)
        {
            Submit.Visible = false;
            Reset.Visible = false;
        }
    }

    //【01】取得問卷基本資料 
    public bool[] GetSurvey(string SURVEY_ID)
    {
        
        SurveyService.SurveyService surveyService = new SurveyService.SurveyService();
        DataTable dt_Survey = surveyService.GetSurvey(SURVEY_ID, "@CMD_CarryCargo");
        bool[] Reult = new bool[2];
        Reult[0] = false;
        Reult[1] = false;

        if (dt_Survey != null)
        {
            if (dt_Survey.Rows.Count > 0)
            {

                Reult[0] = true;
                string CREATOR;
                lbl_SURVEY_SUBJECT.Text = dt_Survey.Rows[0]["SURVEY_SUBJECT"].ToString();
                lbl_SURVEY_ID.Text = dt_Survey.Rows[0]["SURVEY_ID"].ToString();
                CREATOR = dt_Survey.Rows[0]["CREATOR"].ToString();
                lbl_GROUP_TEXT.Text = "【" + dt_Survey.Rows[0]["GROUP_TEXT"].ToString() + "】";
                lbl_END_TIME.Text = dt_Survey.Rows[0]["END_TIME"].ToString();
                END_TIME = DateTime.Parse(lbl_END_TIME.Text);
                lbl_CREATOR.Text = Tool_kitcs.GetUserInfo(CREATOR, "");

                if (DateTime.Now > END_TIME)
                  lit_Update.Text = "問卷填答時間已過，謝謝!";
                else 
                  Reult[1] = true;

                return Reult;
            }
            else
                lbl_SURVEY_SUBJECT.Text = "查無問卷";

        }


        return Reult;
    }

    //【02-01】取得題目
    public void GetQuestion(string SURVEY_ID)
    {
        SurveyService.SurveyService surveyService = new SurveyService.SurveyService();
        DataTable dt_Question = surveyService.GetQuestion(SURVEY_ID, "@CMD_CarryCargo");

        if (dt_Question != null)
        {
            if (dt_Question.Rows.Count > 0)
            {
                for (int i = 0; i < dt_Question.Rows.Count; i++)
                {
                    int CHOICE_NUM;
                    string QUESTION_ID, QUESTION_TEXT;
                    CHOICE_NUM = int.Parse(dt_Question.Rows[i]["CHOICE_NUM"].ToString());
                    QUESTION_ID = dt_Question.Rows[i]["QUESTION_ID"].ToString();
                    QUESTION_TEXT = dt_Question.Rows[i]["QUESTION_TEXT"].ToString();
                    this.PlaceHolder1.Controls.Add(
                    new LiteralControl("<fieldset class='radios'>"));
                    this.PlaceHolder1.Controls.Add(new LiteralControl((i + 1).ToString() + ". " + QUESTION_TEXT));


                    //【02-02】取得答案選項
                    GetAnswer(SURVEY_ID, QUESTION_ID, CHOICE_NUM);
                    //TextBox txtBox = new TextBox();
                    //txtBox.ID = SURVEY_ID + "_" + QUESTION_ID+"_txt";
                    //this.PlaceHolder1.Controls.Add(txtBox);
                    if (!IsPostBack) GetUserAnswer(SURVEY_ID, QUESTION_ID, SIP_NO);
                    Label lblBox = new Label();
                    lblBox.ID = QUESTION_ID + "_lbl";
                    this.PlaceHolder1.Controls.Add(lblBox);
                    this.PlaceHolder1.Controls.Add(new LiteralControl("</fieldset>"));
                    this.PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
                }
            }
        }
    }

    //【02-02】取得答案選項
    public void GetAnswer(string SURVEY_ID, string QUESTION_ID, int CHOICE_NUM)
    {
        SurveyService.SurveyService surveyService = new SurveyService.SurveyService();
        DataTable dt_Answer = surveyService.GetAnswer(SURVEY_ID, QUESTION_ID, CHOICE_NUM, "@CMD_CarryCargo");

        if (dt_Answer != null)
        {
            if (dt_Answer.Rows.Count > 0)
            {
                if (CHOICE_NUM == 1)
                {
                    RadioButtonList rdoList = new RadioButtonList();
                    rdoList.ID = SURVEY_ID + "_" + QUESTION_ID;
                    for (int i = 0; i < dt_Answer.Rows.Count; i++)
                    {
                        ListItem itmList = new ListItem(
                          dt_Answer.Rows[i]["ANSWER_TEXT"].ToString() + "　[ " +
                          dt_Answer.Rows[i]["ANSWER_VALUE"].ToString() + " ]",
                          SURVEY_ID + "|" +
                          dt_Answer.Rows[i]["QUESTION_ID"].ToString() + "|" +
                          dt_Answer.Rows[i]["ANSWER_ID"].ToString());
                        rdoList.Items.Add(itmList);
                        
                    }

                    //ListItem itmListOther = new ListItem("其他",
                    //SURVEY_ID + "|" +
                    //dt_Answer.Rows[0]["QUESTION_ID"].ToString()+
                    //"|Other");
                    //rdoList.Items.Add(itmListOther);


                    rdoList.CssClass = "radios";
                    this.PlaceHolder1.Controls.Add(rdoList);
                }
                else
                {
                    CheckBoxList chkList = new CheckBoxList();
                    chkList.ID = SURVEY_ID + "_" + QUESTION_ID;
                    for (int i = 0; i < dt_Answer.Rows.Count; i++)
                    {
                        ListItem itmList = new ListItem(
                          dt_Answer.Rows[i]["ANSWER_TEXT"].ToString() + "　[ $" +
                          dt_Answer.Rows[i]["ANSWER_VALUE"].ToString() + " ]",
                          SURVEY_ID + "|" +
                          dt_Answer.Rows[i]["QUESTION_ID"].ToString() + "|" +
                          dt_Answer.Rows[i]["ANSWER_ID"].ToString());
                        chkList.Items.Add(itmList);
                    }
                    this.PlaceHolder1.Controls.Add(chkList);
                }
            }
        }
    }


    //【02-03】取得USER作答結果
    public void GetUserAnswer(string SURVEY_ID, string QUESTION_ID, string SIP_NO)
    {
        SurveyService.SurveyService surveyService = new SurveyService.SurveyService();
        DataTable dt_Answer = surveyService.GetUserAnswer(SURVEY_ID,
          QUESTION_ID,
          SIP_NO,
          "@CMD_CarryCargo");

        if (dt_Answer != null)
        {
            if (dt_Answer.Rows.Count > 0)
            {
                for (int i = 0; i < dt_Answer.Rows.Count; i++)
                {
                    string ANSWER_ID = dt_Answer.Rows[i]["ANSWER_ID"].ToString();
                    RadioButtonList rdoList = (RadioButtonList)FindControl(SURVEY_ID + "_" + QUESTION_ID);
                    rdoList.SelectedValue = SURVEY_ID + "|" + QUESTION_ID + "|" + ANSWER_ID;
                }
            }
        }
    }

    //【03】送出問卷
    protected void Submit_Click(object sender, EventArgs e)
    {

      string[] strAnswer;
      string[] strQuestion;
      ArrayList list = new ArrayList();
      bool result;

        if (DateTime.Now > END_TIME)
        {
            lit_Update.Text = "問卷填答時間已過，謝謝!";
        }
        else
        {


            foreach (Control control in PlaceHolder1.Controls)
            {
              //單選題
              if (control is RadioButtonList) {
                RadioButtonList rdoList = (RadioButtonList)control;
                strQuestion = control.ID.Split('_');
                result = DelAnswer(strQuestion[0], strQuestion[1], SIP_NO);
                strAnswer = rdoList.SelectedValue.Split('|');
                if (strAnswer.Length == 3) {
                  if (strAnswer[2] == "Other") {
                    Control ctrl = FindControl(strAnswer[0] + "_" + strAnswer[1] + "_txt");
                    TextBox txtBox = (TextBox)ctrl;
                    Response.Write(txtBox.Text);
                  }
                  else
                    result = InsertAnswer(strAnswer[0], strAnswer[1], strAnswer[2], SIP_NO);
                }

              }

              DisEditControls();
              lit_Update.Text = "感謝填答，問卷完成送出!";
            }
        }

    }

    //【04-01】清空選項
    protected void Reset_Click(object sender, EventArgs e)
    {
        ResetAllControls();
        Submit_Click(null, null);
    }

    //【04-01】清空選項
    public void ResetAllControls()
    {
        foreach (Control control in PlaceHolder1.Controls)
        {
            if (control is RadioButtonList)
            {
                RadioButtonList rdoList = (RadioButtonList)control;
                rdoList.SelectedIndex = -1;
            }
        }
    }

    //【04-02】Disable選項
    public void DisAllControls() {
      foreach (Control control in PlaceHolder1.Controls) {
        if (control is RadioButtonList) {
          RadioButtonList rdoList = (RadioButtonList)control;
          rdoList.Enabled = false;
          rdoList.Visible = false;
          rdoList.CssClass = "DisRadios";
          String[] strQuestion = rdoList.ID.Split('_');
          Label lblBox = (Label)FindControl(strQuestion[1] + "_lbl");
          lblBox.Font.Bold = true;
          if (rdoList.SelectedIndex >= 0)
            lblBox.Text = "<br><br>　　您選擇的是 " + rdoList.SelectedItem.Text + "<br><br>";
          else
            lblBox.Text = "<br><br>　　您尚未選擇<br><br>";

        }
      }
      Edit.Visible = false;
      Submit.Visible = false;
      Reset.Visible = false;
    }

    public void DisEditControls() {
      foreach (Control control in PlaceHolder1.Controls) {
        if (control is RadioButtonList) {
          RadioButtonList rdoList = (RadioButtonList)control;
          rdoList.Enabled = false;
          rdoList.Visible = false;
          rdoList.CssClass = "DisRadios";
          String[] strQuestion = rdoList.ID.Split('_');
          Label lblBox = (Label)FindControl(strQuestion[1] + "_lbl");
          lblBox.Font.Bold = true;
          if (rdoList.SelectedIndex >= 0)
            lblBox.Text = "<br><br>　　您選擇的是 " + rdoList.SelectedItem.Text + "<br><br>";
          else
            lblBox.Text = "<br><br>　　您尚未選擇<br><br>";

        }
      }
      Edit.Visible = true;
      Submit.Visible = false;
      Reset.Visible = false;
    }

    //【04-02】Enable選項
    public void EnAllControls()
    {
        foreach (Control control in PlaceHolder1.Controls)
        {

            if (control is RadioButtonList)
            {
                RadioButtonList rdoList = (RadioButtonList)control;
                rdoList.Enabled = true;
                rdoList.Visible = true;
                rdoList.CssClass = "radios";

                String[] strQuestion = rdoList.ID.Split('_');
                Label lblBox = (Label)FindControl(strQuestion[1] + "_lbl");
                lblBox.Text = "";
            }

        }
    }

    //【05-01】新增答案
    public bool InsertAnswer(string SURVEY_ID,
      string QUESTION_ID,
      string ANSWER_ID,
      string SIP_NO)
    {
        SurveyService.SurveyService surveyService = new SurveyService.SurveyService();
        bool result = surveyService.InsertAnswer(SURVEY_ID,
          QUESTION_ID,
          ANSWER_ID,
          SIP_NO,
          "@CMD_CarryCargo");
        return result;
    }

    //【05-02】刪除答案
    public bool DelAnswer(string SURVEY_ID,
      string QUESTION_ID,
      string SIP_NO)
    {
        SurveyService.SurveyService surveyService = new SurveyService.SurveyService();
        bool result = surveyService.DelAnswer(SURVEY_ID,
          QUESTION_ID,
          SIP_NO,
          "@CMD_CarryCargo");
        return result;
    }

    //【05-03】新增選項
    public bool InsertAnswerData(string SURVEY_ID,
      string QUESTION_ID,
      string SIP_NO,
      string ANSWER_TEXT,
      string ANSWER_VALUE) {
      SurveyService.SurveyService surveyService = new SurveyService.SurveyService();
      bool result = surveyService.InsertAnswerData(SURVEY_ID,
        QUESTION_ID,
        ANSWER_TEXT,
        ANSWER_VALUE,
        SIP_NO,
        "@CMD_CarryCargo");
      return result;
    }

    ////【05-04】新增其他
    //public bool InsertAnswerOther(string SURVEY_ID,
    //  string QUESTION_ID,
    //  string SIP_NO,
    //  string ANSWER_TEXT,
    //  string ANSWER_VALUE) {
    //  SurveyService.SurveyService surveyService = new SurveyService.SurveyService();
    //  bool result = surveyService.InsertAnswerData(SURVEY_ID,
    //    QUESTION_ID,
    //    OTHER_TEXT,
    //    ANSWER_VALUE,
    //    SIP_NO,
    //    "@CMD_CarryCargo");
    //  return result;
    //}

    protected void Edit_Click(object sender, EventArgs e)
    {
        lit_Update.Text = "";
        Submit.Visible = true;
        Reset.Visible = true;
        Edit.Visible = false;
        EnAllControls();
    }

    //登入驗證
    private void UserAuthorization()
    {
        try
        {
            Application.Lock();
            ArrayList app_session_id = (ArrayList)Application.Get("LIVE_SESSION");
            ArrayList app_sip_number = (ArrayList)Application.Get("SIP_NUMBER");
            ArrayList app_time_stamp = (ArrayList)Application.Get("TIME_STAMP");
            Application.UnLock();

            string page_session_id = Session.SessionID;

            if ((Request.QueryString[CF.QS_sip_number] != null) && (Request.QueryString[CF.QS_time_stamp] != null))
            {
                //先不加密
                /*
                string page_sip_number = Request.QueryString[CF.QS_sip_number].ToString();
                string page_time_stamp = Request.QueryString[CF.QS_time_stamp].ToString();
                */

                //加密
                string page_sip_number = CF.DecodeString(Request.QueryString[CF.QS_sip_number].ToString());
                string page_time_stamp = CF.DecodeString(Request.QueryString[CF.QS_time_stamp].ToString());

                //顯示登入資訊
                //CustomNameLabel.Text = page_custom_name;
                //UserDirLabel.Text = page_user_dir;

                //**驗證使用者資訊**
                if (app_sip_number.Contains(page_sip_number) && app_time_stamp.Contains(page_time_stamp))
                {
                    //do nothing
                }
                else
                {
                    //Response.Write("使用者沒經過驗證直接到這頁!");
                    ClearSessionVariables();
                    Response.Redirect(CF.RedirectPage + Request.Url.Query);
                }

                //**驗證各種重複登入**
                //找出sip_number的index
                int index = app_sip_number.IndexOf(page_sip_number);
                if (index != -1)
                {
                    //sip_number相同, session_id不同 > 使用者在別處用自己的sip_number登入
                    //每次Page_Load時檢查page.sessionid和app_session_id相不相同, 不同就登出
                    if (app_session_id[index].ToString() != page_session_id)
                    {
                        ClearSessionVariables();
                        Response.Redirect(CF.RedirectPage + Request.Url.Query);
                        //Response.Write("session id 不同, 跳回登入頁面<BR>");
                    }
                    else
                    {
                        //Response.Write("session_id 相同, ok<BR>");

                        //sip_number相同, session_id也相同 > 檢查time_stamp是否也相同
                        //time_stamp若不同, 代表同一個瀏覽器多頁籤登入, 登出較早登入的連線
                        if (app_time_stamp[index].ToString() != page_time_stamp)
                        {
                            ClearSessionVariables();
                            Response.Redirect(CF.RedirectPage + Request.Url.Query);
                            //Response.Write("time_stamp 不同, 跳回登入頁面<BR>");
                        }
                        //time_stamp若相同, 則合法登入
                        else
                        {
                            //Response.Write("time_stamp 相同, ok<BR>");

                            //合法登入, 不做事
                        }
                    }
                }
                else
                {
                    //app_sip_number中找不到page_sip_number
                    ClearSessionVariables();
                    Response.Redirect(CF.RedirectPage + Request.Url.Query);
                    //Response.Write("index = -1, 跳回登入頁面<BR>");
                }
            }
            else
            {
                //直接打網址進入此頁
                ClearSessionVariables();
                Response.Redirect(CF.RedirectPage + Request.Url.Query);
            }
        }
        catch (Exception ex)
        {
            //ShowErrorMessage(ex.TargetSite.ToString() + ex.Message);
        }
    }
    private void ClearSessionVariables()
    {
        Session.RemoveAll();
    }
}